let postUrl = "http://121.43.153.61:9090";
let token = "Bearer " + window.GlobalToken;
let liscode = null

//获取弹窗
let window_bg = document.getElementsByClassName("window_bg")[0];
let timer = null;

//点击弹窗外部可隐藏弹窗
window.onclick = function (event) {
  if (event.target == window_bg) {
    event.target.style.display = "none";
    clearCache()
  }
};

function closeFun() {
  window_bg.style.display = "none";
  clearCache()

  //可根据需要调整事件
}
// 点击按钮显示弹窗
function show() {
  let result = `weixin://wxpay/bizpayurl?pr=fUaoW2hz3`
  // qrcode.makeCode(result);
  window_bg.style.display = "block";
  let window_text_c_img = document.querySelector(".window_text_c_img");
  window_text_c_img.style.display = "none";
  let window_text_t_red = document.querySelector(".window_text_t_red");
  let money = localStorage.getItem("money");
  window_text_t_red.innerHTML = money
  var qrcode = new QRCode("qrcode", {
    text: result,	//要生成二维码的链接
    width: 125,	//二维码的宽度
    height: 125,	//二维码的高度
    colorDark: "#000000",	//前景色
    colorLight: "#ffffff",	//背景色
    correctLevel: QRCode.CorrectLevel.H	//纠错等级
  });

  // window_bg.style.display = "block";
  // let doc = `<form name=\"punchout_form\" method=\"post\" action=\"https://openapi.alipay.com/gateway.do?charset=UTF-8&method=alipay.trade.page.pay&sign=Rw12GkBlD70YE%2Bx8JzNF4N93btx9t%2BnQbc7JraXw259Dpp8jG5d8SnxJe32DyNFAbTxx4xcIjJlDDJ8tAdPmSlD81zxikYtWoI1pK1bVZplZTVQU0efQDoPMgxolrkgUFXfb751KhL2wgFRVaZgHbqofha8z%2F6gk4nJDVv0rFinxNF4TaGIO%2Bc7Mpoh6gSn3YtN4k3N%2B7eHYzdUMN17MBvcPomm6T61A0u9GD%2Bl7dr%2FEalObndNvy%2FCQIDk5OLjcHVWMCNP%2FVPDAsC9SHwXYCpX8xwbsvMGeVkjhbP2Mvd2a07IEV%2BWrcY7%2FktEm%2BjNU3qhpp0hV%2BTuPAPg2N4Ycww%3D%3D&return_url=http%3A%2F%2Fwww.baidu.com&notify_url=http%3A%2F%2F9979.free.idcfengye.com%2Fpay%2Fcallback%2Falipay&version=1.0&app_id=2021004155691203&sign_type=RSA2&timestamp=2024-07-04+17%3A23%3A15&alipay_sdk=alipay-sdk-java-4.39.113.ALL&format=json\">\n<input type=\"hidden\" name=\"biz_content\" value=\"{&quot;integration_type&quot;:&quot;PCWEB&quot;,&quot;out_trade_no&quot;:&quot;1808793685129232384&quot;,&quot;product_code&quot;:&quot;FAST_INSTANT_TRADE_PAY&quot;,&quot;qr_pay_mode&quot;:&quot;4&quot;,&quot;qrcode_width&quot;:120,&quot;request_from_url&quot;:&quot;https:\\/\\/&quot;,&quot;subject&quot;:&quot;吃啥&quot;,&quot;time_expire&quot;:&quot;2024-07-04 17:53:15&quot;,&quot;total_amount&quot;:&quot;0.01&quot;}\">\n<input type=\"submit\" value=\"立即支付\" style=\"display:none\" >\n</form>\n<script>document.forms[0].submit();</script>`
  // let ifname = document.querySelector("#ifname");
  // ifname.srcdoc = doc; // 你想嵌入的网址
  // ifname.width = "125px";
  // ifname.height = "125px";
  // const div = document.createElement("div");
  // console.log("我是后端返回的数据:" + doc);
  // div.innerHTML = doc;
  // document.body.appendChild(div);
  // console.log("punchout_form:" + document.forms.punchout_form);
  // document.forms.punchout_form.submit();

}
function getList() {
  $.ajax({
    url: postUrl + "/api/v1/shop/recharge/list",
    method: "get",
    // 通过headers对象设置请求头
    headers: { "Content-Type": "application/json", Authorization: token },
    data: {},
    dataType: "json",
    //async: true,
    success: function (res) {
      if (res.code === 200) {
        let list = res.data;
        let content = document.querySelector("#rechargeList");
        let listStr = "";
        list.forEach((item, index) => {
          listStr += `
          <div class="item" onclick="getMoney(${item.id},${item.price},${index})">
              <div class="item_t">
                <img src="./static/img/8.png" alt="" class="t_img">
                <span class="coins">${item.coins}金币</span>
                <span class="ids">${item.id}</span>
              </div>
              <div class="item_c">
                <span class="cny">CNY</span>
                <span class="money">${item.price}</span>
              </div>
              <div class="item_b">原价${item.price}</div>
            </div>
                    `;
        });
        content.innerHTML = listStr;
        var lis = content.querySelectorAll(".item");
        lis[0].classList.add('items');
        let id = list[0].id
        let price = list[0].price
        localStorage.setItem("id", id);
        localStorage.setItem("money", price);
      }
    },
    error: function (e) { },
  });
}


function getMoney(id, price, index) {
  console.log(id, price)
  var lis = document.querySelector("#rechargeList").querySelectorAll(".item");
  for (var i = 0; i < lis.length; i++) {
    lis[i].classList.remove('items');
    lis[index].classList.add('items');
  }
  localStorage.setItem("id", id);
  localStorage.setItem("money", price);
}
function getModeType(text) {
  let typeItem = document.querySelector(".typeItem");
  let typeItem1 = document.querySelector(".typeItem1");
  let typeItem2 = document.querySelector(".typeItem2");
  let mode = "";
  if (text == "聚合码") {
    mode = 0;
    typeItem1.classList.remove('typeItems');
    typeItem2.classList.remove('typeItems');
    typeItem.classList.add('typeItems');
    toast.show('聚合码暂未开通', 2000)
    clearCache()
  } else if (text == "微信") {
    mode = 1;
    typeItem.classList.remove('typeItems');
    typeItem2.classList.remove('typeItems');
    typeItem1.classList.add('typeItems');
  } else if (text == "支付宝") {
    mode = 2;
    typeItem.classList.remove('typeItems');
    typeItem1.classList.remove('typeItems');
    typeItem2.classList.add('typeItems');
  }
  localStorage.setItem("mode", mode);
  createOrder();
}

// 创建订单
function createOrder() {
  let mode = localStorage.getItem("mode");
  let money = localStorage.getItem("money");
  let id = localStorage.getItem("id");
  let data = {
    shopRechargeId: id,
    price: money,
    payType: mode,
  };
  $.ajax({
    url: postUrl + "/api/v1/shop/recharge/order",
    method: "post",
    headers: { "Content-Type": "application/json", Authorization: token },
    data: JSON.stringify(data),
    dataType: "json",
    success: function (res) {
      if (res.code === 200) {
        if (id != null) {
          alipay(res.data.orderNo);
        } else {
          toast.show('请先选择套餐包', 2000)
        }
      } else {
        // toast.show('创建订单失败', 2000)
        toast.show('请先选择套餐包', 2000)
        clearCache()
      }
    },
    error: function (e) {
      toast.show('创建订单失败', 2000)
      clearCache()
    },
  });
}
// 支付宝支付
function alipay(orderNo) {
  let data = {
    orderNo
  }
  $.ajax({
    url: postUrl + "/api/v1/shop/recharge/order/pay",
    method: "post",
    headers: { "Content-Type": "application/json", Authorization: token },
    data: JSON.stringify(data),
    dataType: "json",
    success: function (res) {
      if (res.code === 200) {
        getStatus(res.msg)
        timer = setInterval(() => {
          getAjax(orderNo)
        }, 1500)
      }
    },
    error: function (e) {
      toast.show('支付失败', 2000)
    },
  });
}
function getStatus(result) {
  let mode = localStorage.getItem("mode");
  let money = localStorage.getItem("money");
  let qrcode = document.querySelector("#qrcode");
  let window_text_t = document.querySelector(".window_text_t");
  let window_text_c = document.querySelector(".window_text_c");
  let window_text_c_img = document.querySelector(".window_text_c_img");
  let window_text_c_img_s = document.querySelector(".window_text_c_img_s");
  let window_text_t_red = document.querySelector(".window_text_t_red");
  let ifname = document.querySelector("#ifname");

  if (mode == 1) {
    window_bg.style.display = "block";
    qrcode.style.display = "block";
    window_text_c.style.display = "none";
    window_text_c_img.style.display = "none";
    window_text_c_img_s.style.display = "none";
    window_text_t.innerHTML = `请用微信扫一扫付款`
    window_text_t_red.innerHTML = money

    liscode = new QRCode("qrcode", {
      text: result,	//要生成二维码的链接
      width: 125,	//二维码的宽度
      height: 125,	//二维码的高度
      colorDark: "#000000",	//前景色
      colorLight: "#ffffff",	//背景色
      correctLevel: QRCode.CorrectLevel.H	//纠错等级
    });

  } else if (mode == 2) {
    window_bg.style.display = "block";
    qrcode.style.display = "none";
    window_text_c.style.display = "block";
    window_text_c_img.style.display = "none";
    window_text_c_img_s.style.display = "none";
    window_text_t.innerHTML = `请用支付宝扫一扫付款`
    window_text_t_red.innerHTML = money
    ifname.srcdoc = result; // 你想嵌入的网址
    ifname.width = "125px";
    ifname.height = "125px";
  }

}
// 查询状态
function getAjax(orderNo) {
  let data = {
    orderNo
  }
  $.ajax({
    url: postUrl + "/api/v1/shop/recharge/order/status",
    method: "get",
    headers: { "Content-Type": "application/json", Authorization: token },
    data: data,
    dataType: "json",
    success: function (res) {
      if (res.code === 200) {
        if (res.data.payStatus === 2) {
          let window_text_c = document.querySelector(".window_text_c");
          let qrcode = document.querySelector("#qrcode");
          let window_text_c_img = document.querySelector(".window_text_c_img");
          window_text_c.style.display = "none";
          qrcode.style.display = "none";
          window_text_c_img.style.display = "block";
          // 支付成功
          window.ndkPaymentFinish()
          clearCache()
        } else if (res.data.payStatus === 4) {
          let window_text_c = document.querySelector(".window_text_c");
          let qrcode = document.querySelector("#qrcode");
          let window_text_c_img_s = document.querySelector(".window_text_c_img_s");
          window_text_c.style.display = "none";
          qrcode.style.display = "none";
          window_text_c_img_s.style.display = "block";
          // 支付失败
          clearCache()
        }
      }
    },
    error: function (e) {
    },
  });
}


function clearCache() {
  let typeItem = document.querySelector(".typeItem");
  let typeItem1 = document.querySelector(".typeItem1");
  let typeItem2 = document.querySelector(".typeItem2");
  let qrcode = document.querySelector("#qrcode");
  typeItem.classList.remove('typeItems');
  typeItem1.classList.remove('typeItems');
  typeItem2.classList.remove('typeItems');
  var lis = document.querySelector("#rechargeList").querySelectorAll(".item");
  for (var i = 0; i < lis.length; i++) {
    lis[i].classList.remove('items');
  }
  localStorage.removeItem("mode");
  localStorage.removeItem("money");
  localStorage.removeItem("id");
  clearInterval(timer)
  qrcode.innerHTML = ''
  liscode.clear();
}

getList();
